package com.alex.wechat.mp.welcome.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.config.WxContext;
import com.alex.wechat.mp.message.news.entity.WxNewsTemplate;
import com.alex.wechat.mp.message.news.service.WxNewsTemplateServiceI;
import com.alex.wechat.mp.message.text.entity.WxTextTemplate;
import com.alex.wechat.mp.message.text.service.WxTextTemplateServiceI;
import com.alex.wechat.mp.welcome.entity.WxWelcomeEntity;
import com.alex.wechat.mp.welcome.service.WxWelcomeServiceI;

/**
 * 关注管理
 * 
 */
@Controller
@RequestMapping("/wxWelcomeController")
public class WxWelcomeController {

  @Autowired
  private SystemService systemService;
  @Autowired
  private WxWelcomeServiceI welcomeService;
  @Autowired
  private WxTextTemplateServiceI textTemplateService;
  @Autowired
  private WxNewsTemplateServiceI newsTemplateService;

  @RequestMapping(params = "list")
  public ModelAndView list() {
    return new ModelAndView("com/gomore/wechat/mp/welcome/welcomeList");
  }

  @RequestMapping(params = "datagrid")
  @ResponseBody
  public void datagrid(WxWelcomeEntity welcome, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    CriteriaQuery cq = new CriteriaQuery(WxWelcomeEntity.class, dataGrid);
    cq.eq("accountId", WxContext.getOriginalId());
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, welcome);
    this.welcomeService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }

  @RequestMapping(params = "del")
  @ResponseBody
  public AjaxJson deleteSmsGroup(WxWelcomeEntity welcome, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    welcome = this.welcomeService.getEntity(WxWelcomeEntity.class, welcome.getId());
    this.welcomeService.delete(welcome);
    String message = "删除信息数据成功！";
    systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    j.setMsg(message);
    return j;
  }

  @RequestMapping(params = "edit")
  public ModelAndView showEditView(HttpServletRequest req) {
    String id = req.getParameter("id");
    req.setAttribute("id", id);

    List<WxTextTemplate> textList = textTemplateService
        .getAllByAccountId(WxContext.getOriginalId());
    req.setAttribute("textList", textList);

    List<WxNewsTemplate> newsLists = newsTemplateService
        .getAllByAccountId(WxContext.getOriginalId());
    req.setAttribute("newsList", newsLists);

    if (StringUtil.isNotEmpty(id)) {
      WxWelcomeEntity subscribe = this.welcomeService.getEntity(WxWelcomeEntity.class, id);
      String lx = subscribe.getMsgType();
      String templateId = subscribe.getTemplateId();
      req.setAttribute("lx", lx);
      req.setAttribute("templateId", templateId);
      req.setAttribute("subscribe", subscribe);
    }

    return new ModelAndView("com/gomore/wechat/mp/welcome/welcome");
  }

  @RequestMapping(params = "save")
  @ResponseBody
  public AjaxJson save(WxWelcomeEntity welcome, HttpServletRequest req) {
    AjaxJson j = new AjaxJson();
    if (!WxContext.hasWxAccount()) {
      j.setSuccess(false);
      j.setMsg("请添加一个公众帐号。");
      return j;
    }

    String message = null;
    String id = welcome.getId();
    if (StringUtil.isNotEmpty(id)) {
      // 新增保存
      WxWelcomeEntity tempAutoResponse = welcomeService.getEntity(WxWelcomeEntity.class,
          welcome.getId());
      try {
        MyBeanUtils.copyBeanNotNull2Bean(welcome, tempAutoResponse);
        this.welcomeService.saveOrUpdate(tempAutoResponse);
        message = "修改关文本模板成功！";
        j.setMsg(message);
        systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
      } catch (Exception e) {
        j.setSuccess(false);
        j.setMsg("保存失败: " + e.getMessage());
      }

    } else {
      // 判断当前公众帐号是否已经配置欢迎语
      WxWelcomeEntity oldWelcome = welcomeService.getByAccountId(WxContext.getOriginalId());
      if (oldWelcome != null) {
        j.setSuccess(false);
        j.setMsg("每个公众帐号只能配置一个欢迎语。");
        return j;
      }

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      welcome.setAddTime(sdf.format(new Date()));
      String templateId = welcome.getTemplateId();
      String msgType = welcome.getMsgType();
      String templateName = "";
      if ("text".equals(msgType)) {
        WxTextTemplate textTemplate = this.welcomeService.getEntity(WxTextTemplate.class,
            templateId);
        if (textTemplate != null) {
          templateName = textTemplate.getTemplateName();
        }
      } else if ("news".equals(msgType)) {
        WxNewsTemplate newsTemplate = this.welcomeService.getEntity(WxNewsTemplate.class,
            templateId);
        if (newsTemplate != null) {
          templateName = newsTemplate.getTemplateName();
        }
      }
      welcome.setTemplateName(templateName);
      welcome.setAccountId(WxContext.getOriginalId());
      this.welcomeService.save(welcome);
      j.setMsg("保存成功");
    }

    return j;
  }

}